clear all

global replica_dir="<add path to your working directory>"
global data_dir=	"$replica_dir/data"
global output_dir=	"$replica_dir/output"


global simce_data_dir="<add path to your SIMCE data directory>"
*------------------------------------------------------------------------------*

* SIMCE 2013 4b

*------------------------------------------------------------------------------*

**# Student scores

/*----------------------------------------------------------------------------*/

use "$simce_data_dir/4B/simce4b2013/Archivos DTA (Stata)/simce4b2013_alu_publica_final.dta", clear

keep if noptje_lect4b_alu==0 | noptje_mate4b_alu==0 | noptje_nat4b_alu==0   

duplicates report mrun
duplicates examples mrun
duplicates tag mrun, g(ndupobs)
unique mrun

keep if ndupobs==0

rename  (ptje_lect4b_alu 	ptje_mate4b_alu 	ptje_nat4b_alu ) /// 
		(lect_pre			mate_pre			nat_pre)

keep idalumno mrun rbd lect_pre mate_pre  nat_pre

save "$data_dir/simce_b4_2013.dta", replace


*------------------------------------------------------------------------------*

**#  Parental survey

*------------------------------------------------------------------------------*

use "$simce_data_dir/4B/simce4b2013/Archivos DTA (Stata)/simce4b2013_cpad_publica_final.dta", clear


foreach var of varlist cpad_*{
replace `var'=. if `var'==0 | `var'==99
}


gen 	dad_edu_pre=.
replace dad_edu_pre=cpad_p07
replace dad_edu_pre=. if cpad_p07==0 | cpad_p07==21

gen 	mom_edu_pre=.
replace mom_edu_pre=cpad_p08 
replace mom_edu_pre=. if cpad_p08==0 | cpad_p08==21

gen 	pad_inc_pre=.
replace pad_inc_pre=cpad_p10
replace pad_inc_pre=. if cpad_p10==0  

keep idalumno dad_edu_pre mom_edu_pre pad_inc_pre

merge 1:1 idalumno using "$data_dir/simce_b4_2013.dta" 
drop _merge

sort mrun

save "$data_dir/simce_b4_2013.dta", replace




*------------------------------------------------------------------------------*

**#  School survey

*------------------------------------------------------------------------------*

use "$simce_data_dir/4B/simce4b2013/Archivos DTA (Stata)/simce4b2013_rbd_publica_final.dta", clear

egen sch_stno_pre = rowmax(nalu_4b_rbd nalu_lect4b_rbd nalu_mate4b_rbd nalu_nat4b_rbd)

rename 	(cod_depe1		cod_grupo 		cod_reg_rbd) ///
		(sch_depe1_pre	sch_gse_pre 	cod_reg_rbd_pre)

keep  rbd sch_stno_pre sch_depe1_pre sch_gse_pre cod_reg_rbd_pre

merge 1:m rbd using "$data_dir/simce_b4_2013.dta"

////browse if _merge==1
keep if _merge==3
drop _merge


drop idalumno
rename rbd rbd_pre
sort mrun

save "$data_dir/simce_b4_2013.dta", replace

*------------------------------------------------------------------------------*
